package com.example.librarymanagement.config;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.librarymanagement.result.PageResult;
import com.example.librarymanagement.result.Result;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @author fgba
 * @version 1.0.0
 * @date Create in 2020/11/15
 */
@RestControllerAdvice(basePackages = "com.example.librarymanagement.controller")
@Configuration
public class GlobalReturnConfig implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {

        //处理 controller 中返回void的操作
        if (body == null) {
            return Result.success();
        }

        //检测body是不是已经封装成了 Result 对象
        if (body instanceof Result) {
            return body;
        }

        //检测是否返回 IPage
        if (body instanceof IPage) {
            IPage page = (IPage) body;
            return PageResult.success(page.getRecords(), page.getTotal());
        }

        return Result.success(body);
    }
}

